<template>
  <basic-container>
    <el-collapse>
      <el-collapse-item name="1">
        <template #title>
          <el-text type="info">
            <el-icon>
              <Warning />
            </el-icon>
            提示：
          </el-text>
        </template>
        <div>
          <el-text type="info">
            1.“导出库存”，会将所有商品信息导出
          </el-text>
        </div>
        <div>
          <el-text type="info">
            2.”导入库存”，导入的模板即为“导出库存”，下载作为模板。
          </el-text>
        </div>
        <div>
          <el-text type="info">
            3. Excel中”库存数量“，”参考单价“请认真检查，"库存价值"在导入后会
           <span style="color: red;">重新计算: 库存价值 = 库存数量 * 参考单价</span>
          </el-text>
        </div>
        <div>
          <el-text type="info">
            4. 导入的模板中，请勿修改列名、以及隐藏项”id“（作为商品ID导入依据）
          </el-text>
        </div>
      </el-collapse-item>
    </el-collapse>



    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:search="search"
               v-model:page="page"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.purchasecommodity_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   icon="el-icon-download"
                   v-if="permission.purchasecommodity_edit"
                   @click="handleExport">导出库存
        </el-button>
        <el-button type="success"
                   plain
                   icon="el-icon-upload"
                   v-if="permission.purchasecommodity_edit"
                   @click="handleImport">导入库存
        </el-button>
      </template>

      <template #stockUnit="{row}">
        <el-text v-if="row.stockUnit" type="warning">{{ row.stockUnit }}</el-text>
        <el-text v-else>{{ row.unit }}</el-text>
      </template>

    </avue-crud>

    <el-dialog title="导入库存"
               append-to-body
               v-model="excelBox"
               width="555px">
      <avue-form :option="excelOption"
                 v-model="excelForm"
                 :upload-after="uploadAfter">
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/restaurant/purchasecommodity';
import { getCategoryDic } from '@/api/restaurant/purchasecategory';
import { mapGetters } from 'vuex';
import { serialize } from '@/utils/util';
import { getToken } from '@/utils/auth';
import { baseUrl } from '@/config/env';

export default {
  data() {
    return {
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: baseUrl + "/restaurant/purchasecommodity/import"
          }
        ]
      },
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        grid: true,
        gridSpan: 4,
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        column: [
          {
            label: '货物名',
            prop: 'commodityName',
            search: true,
            rules: [{
              required: true,
              message: '请输入货物名',
              trigger: 'blur'
            }]
          },

          {
            label: '采购类别',
            prop: 'categoryId',
            type: 'select',
            search: true,
            props: {
              label: 'categoryName',
              value: 'id'
            },
            dicUrl: '/api/restaurant/purchasecategory/dic',
            rules: [{
              required: true,
              message: '请输入采购类别ID',
              trigger: 'blur'
            }]
          },
          {
            label: '货物图',
            prop: 'productPicture',
            type: 'upload',
            listType: 'picture-img',
            size: 'medium',
            span: 24,
            minRows: 4,
            action: '/api/blade-resource/oss/endpoint/put-file',
            accept: 'image/png, image/jpeg',
            tip: '只能上传jpg/png，且不超过10M',
            propsHttp: {
              res: 'data',
              url: 'link'
            },
            rules: [{
              required: true,
              message: '请输入货物图',
              trigger: 'blur'
            }]
          },
          {
            label: '单位',
            prop: 'unit',
            rules: [{
              required: true,
              message: '请输入单位',
              trigger: 'blur'
            }]
          }, {
            label: '库存单位',
            prop: 'stockUnit',
            rules: [{
              required: false,
              message: '请输入库存单位',
              trigger: 'blur'
            }]
          }, {
            label: '库存数量',
            prop: 'stockNumber',
            rules: [{
              required: false,
              message: '请输入库存数量',
              trigger: 'blur'
            }]
          }, {
            label: '参考单价',
            prop: 'referencePrice',
            rules: [{
              required: false,
              message: '请输入参考单价',
              trigger: 'blur'
            }]
          }, {
            label: '库存价值',
            prop: 'stockValue',
            disabled: true,
            rules: [{
              required: false,
              message: '库存价值',
              trigger: 'blur'
            }]
          }

        ]
      },
      data: [],
      categoryList: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.purchasecommodity_add, false),
        viewBtn: this.validData(this.permission.purchasecommodity_view, false),
        delBtn: this.validData(this.permission.purchasecommodity_delete, false),
        editBtn: this.validData(this.permission.purchasecommodity_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    handleImport () {
      this.excelBox = true;
    },
    uploadAfter (res, done, loading, column) {
      window.console.log(column);
      done();
      this.excelBox = false;
      this.refreshChange();
    },
    async handleExport() {
      this.$prompt(`确定导出库存数据? 0 全部商品 1 仅有库存商品`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[01]$/, // 修改这一行
        inputErrorMessage: '只能输入0或1', // 提示信息也相应修改

        type: 'warning'
      }).then(({value}) => {
        this.query.isStock = value
        console.log('导出查询条件：', serialize(this.query));
        window.open(`/api/restaurant/purchasecommodity/export?blade-auth=bearer ${getToken()}&` + serialize(this.query));
      });
    },

    rowSave(row, done, loading) {
      const { categoryName, sort } = this.categoryList.find(item => item.id === row.categoryId);
      row.categoryName = categoryName;
      row.sort = sort;
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      const { categoryName, sort } = this.categoryList.find(item => item.id === row.categoryId);
      row.categoryName = categoryName;
      row.sort = sort;
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;

        getCategoryDic().then(res => {
          this.categoryList = res.data.data;
        });

        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
